package com.smarthome.web.property.controller.system;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smarthome.common.tools.SHACipher;
import com.smarthome.core.propertystaffmanager.PropertyCompanyService;
import com.smarthome.core.user.PropertyEmployeeService;
import com.smarthome.core.user.PropertyUserService;
import com.smarthome.core.user.UserRoleService;
import com.smarthome.domain.bean.ShPropertyCompany;
import com.smarthome.domain.bean.ShUser;
import com.smarthome.domain.common.Result;
import com.smarthome.domain.enums.ShUserSuperFlagEnum;
import com.smarthome.domain.vo.boss.DataGrid;
import com.smarthome.domain.vo.boss.PageHelper;
import com.smarthome.web.property.utils.UserHolder;

/**
 * 用户控制器
 * 
 * @author KongXiangyu
 * 
 */
@Controller
@RequestMapping("/userController")
public class UserController {

    @Resource
    private PropertyUserService propertyUserService; 
    
    @Resource(name="userRoleService")
    private UserRoleService userRoleService;
    
    @Resource(name="propertyEmployeeService")
    private PropertyEmployeeService employeeService;
    
    @Resource(name="propertyCompanyService")
    private PropertyCompanyService companyService;

    /**
     * 获取用户数据表格
     * 
     * @param user
     * @return
     */
    @RequestMapping("/dataGrid")
    @ResponseBody
    public DataGrid dataGrid(ShUser user, PageHelper ph) {
    	if(!UserHolder.isSuperResidence()){
    		user.setResidenceId(UserHolder.getCurrentResidenceId());
    	}
    	
        return propertyUserService.dataGrid(user, ph);
    }

    /**
     * 跳转到添加用户页面
     * 
     * @param request
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage(HttpServletRequest request) {
    	// 小区id
    	Long comId = null;
    	//查询员工
       // 	request.setAttribute("employees", employeeService.PropertyEmployeesByPropertyId(comId));
    	if(!UserHolder.isSuperResidence()){
    		comId = UserHolder.getCurrentResidenceId();
    	}
    	ShPropertyCompany company = new ShPropertyCompany();
    	company.setId(comId);
    	
    	request.setAttribute("companyUser",JSONObject.toJSON(companyService.queryTreeUser(company)) );
    	
    	//查询角色
    	request.setAttribute("role", JSONObject.toJSON(userRoleService.treeByResidenceId(comId)));
    	
        return "/system/userAdd";
    }

    /**
     * 添加用户
     * 
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public Result add(ShUser user) {
        // userService.add(user);
    	//验证用户名不能为空
    	if(StringUtils.isBlank(user.getLoginName())){
    		return Result.failure("登录名不能为空");
    	}
    	
    	//验证用户密码
    	if(StringUtils.isBlank(user.getLoginPwd()) || user.getLoginPwd().length() < 6){
    		return Result.failure("登录密码不能为空并且大于6位数字");
    	}
    	
    	//绑定邦栋用户不能为空
    	if(null == user.getEmployeeId()){
    		return Result.failure("请选择一个物业公司员工");
    	}
    	
    	
    	//验证员工账号是否被注册为用户
    	if(propertyUserService.isRepeat(user)){
    		return Result.failure("登录名字存在重复");
    	}
    	
    	//验证登录名是否重复
    	if(propertyUserService.isRegest(user)){
    		return Result.failure("该员工已注册账号");
    	}
    	propertyUserService.add(user);
    	
        return Result.success("添加成功！");
    }

    /**
     * 跳转到用户修改页面
     * 
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(HttpServletRequest request, Long id) {
        request.setAttribute("user", propertyUserService.queryPropertyUserById(id));
        
        Long rid = null;
    	if(!UserHolder.isSuperResidence()){
    		rid = UserHolder.getCurrentResidenceId();
    	}
      //查询角色
    	request.setAttribute("role", JSONObject.toJSON(userRoleService.treeByResidenceId(rid)));
        
        
        return "/system/userEdit";
    }

    /**
     * 修改用户
     * 
     * @param user
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Result edit(ShUser user) {
    	//验证用户名不能为空
    	if(StringUtils.isBlank(user.getLoginName())){
    		return Result.failure("登录名不能为空");
    	}
    	
    	//验证用户密码
    	if(StringUtils.isBlank(user.getLoginPwd()) || user.getLoginPwd().length() < 6){
    		return Result.failure("登录密码不能为空并且大于6位数字");
    	}
    	propertyUserService.edit(user);
    	//更新资源
    	 UserHolder.reloadAllPrivileges();
    	
        return Result.success("编辑成功！");
    }

    /**
     * 删除用户
     * 
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Result delete(Long id, HttpSession session) {
    //	session.removeAttribute(name);
    	//不能删除当前自己
    	if(UserHolder.getUserId().equals(id)){
    		return Result.failure("不能删除当前登录用户");
    	}
    	ShUser user = propertyUserService.queryPropertyUserById(id);
    	if(null == user){
    		return Result.failure("未找到删除用户");
    	}
    	
    	//不能删除超级管理员
    	if(ShUserSuperFlagEnum.SUPER.getFlag() ==user.getSuperFlag().intValue()){
    		return Result.failure("不能删除超级管理员");
    	}
    	
    	propertyUserService.delete(id);
    	
    	UserHolder.reloadAllPrivileges();
    	return Result.success("删除成功！");
    }

    /**
     * 批量删除用户
     * 
     * @param ids ('0','1','2')
     * @return
     */
    @RequestMapping("/batchDelete")
    @ResponseBody
    public Result batchDelete(String ids, HttpSession session) {
        if(StringUtils.isBlank(ids)  || !ids.matches("^[0-9]+(,[0-9]+)*$")){ //验证传入的数据是否正确
        	return Result.success("删除用户出现异常");
        }
        
        String[] idstrs = ids.split(",");
        Long[] id = new Long[idstrs.length];
    	
        for(int i=0;i<id.length;i++){
        	id[i] = Long.parseLong(idstrs[i]);
        	//验证是否是当前登录用户
        	ShUser user = propertyUserService.queryPropertyUserById(id[i]);
        	if(UserHolder.getUserId().equals(id[i])){
        		return Result.failure("用户【" + user.getLoginName() + "】为当前登录用户，不能删除。");
        	}
        	if(null == user){
        		return Result.failure("未找到删除用户");
        	}
        	
        	//不能删除超级管理员
        	if(ShUserSuperFlagEnum.SUPER.getFlag() ==user.getSuperFlag().intValue()){
        		return Result.failure("不能删除超级管理员");
        	}
        }
        
        propertyUserService.batchDelete(id);
        //移出用户
        UserHolder.reloadAllPrivileges();
        return Result.success("批量删除成功！");
    }

    /**
     * 跳转到批量用户授权用户授权页面
     * 
     * @return
     */
    @RequestMapping("/butchGrantPage")
    public String butchGrantPage(Long[] ids, HttpServletRequest request) {
    	//查询用户
    	request.setAttribute("users", propertyUserService.queryPropertyUsersByIds(ids));
    	Long rid = null;
    	if(!UserHolder.isSuperResidence()){
    		rid = UserHolder.getCurrentResidenceId();
    	}
    	//查询角色菜单
    	request.setAttribute("role", JSON.toJSON(userRoleService.treeByResidenceId(rid)));
    	
    	return "/system/butchUserGrant";
    }
    
    /**
     * 用户授权
     * 
     * @param ids
     * @return
     */
    @RequestMapping("/butchGrant")
    @ResponseBody
    public Result butchGrant(Long[] ids, String roleIds,HttpServletRequest request) {
    	
    	for(Long id : ids){
    		ShUser user = new ShUser();
    		user.setId(id);
    		user.setRoleIds(roleIds);
    		propertyUserService.grant(user);
    	}
    	
    	UserHolder.reloadAllPrivileges();
        return Result.success("授权成功！");
    }
    
    /**
     * 跳转到用户授权页面
     * 
     * @return
     */
    @RequestMapping("/grantPage")
    public String grantPage(Long id, HttpServletRequest request) {
        //查询用户
    	request.setAttribute("user", propertyUserService.queryPropertyUserById(id));
    	Long rid = null;
    	if(!UserHolder.isSuperResidence()){
    		rid = UserHolder.getCurrentResidenceId();
    	}
    	
    	//查询角色菜单
    	request.setAttribute("role", JSON.toJSON(userRoleService.treeByResidenceId(rid)));
    	
        return "/system/userGrant";
    }

    /**
     * 用户授权
     * 
     * @param ids
     * @return
     */
    @RequestMapping("/grant")
    @ResponseBody
    public Result grant(ShUser user) {
    	
    	if(null == user.getId()){
    		return Result.failure("未找到授权用户");
    	}
    	propertyUserService.grant(user);
    	//移出资源菜单
    	UserHolder.reloadAllPrivileges();
        return Result.success("授权成功！");
    }

    /**
     * 跳转到编辑用户密码页面
     * 
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/editPwdPage")
    public String editPwdPage(Long id, HttpServletRequest request) {
        request.setAttribute("user", propertyUserService.queryPropertyUserById(id));
        return "/system/userEditPwd";
    }

    /**
     * 编辑用户密码
     * 
     * @param user
     * @return
     */
    @RequestMapping("/editPwd")
    @ResponseBody
    public Result editPwd(ShUser user) {
    	if(null == user.getId() || StringUtils.isBlank(user.getLoginPwd()) || user.getLoginPwd().length() < 6){
    		return Result.failure("登录密码不能为空，并且大于6位数字");
    	}
    	propertyUserService.editPwd(user);
        return Result.success("编辑成功！");
    }
    
    /**
     * 编辑自己密码密码
     * 
     * @param user
     * @return
     */
    @RequestMapping("/editOwnPwd")
    @ResponseBody
    public Result editOwnPwd(ShUser user,HttpServletRequest request) {
    	String newLoginPwd = request.getParameter("newLoginPwd");
    	if(StringUtils.isBlank(newLoginPwd) || newLoginPwd.length() < 6){
    		return Result.failure("登录密码不能为空，并且大于6位数字");
    	}
    	user.setId(UserHolder.getUserId());
    	ShUser shuser = propertyUserService.queryPropertyUserById(UserHolder.getUserId());
    	try {
			if(!SHACipher.encrypt(user.getLoginPwd()).equals(shuser.getLoginPwd())) return Result.failure("登录密码错误");
		} catch (Exception e) {
			e.printStackTrace();
			 Result.failure("登录密码错误");
		}
    	user.setLoginPwd(newLoginPwd);
    	propertyUserService.editPwd(user);
    	return Result.success("编辑成功！");
    }

}
